package com.bright.controller.admin;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bright.pojo.User;
import com.bright.service.UserService;
import com.bright.utils.AjaxResult;
import com.bright.utils.MD5Utils;
import com.bright.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class IndexController {

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public AjaxResult Login(@RequestParam String username,@RequestParam String password){
        User user = userService.checkUser(username, MD5Utils.code(password));
//        session.setAttribute("user",user);
        if (user==null)
        {
            return null;
        }
        else {
    //        随机生成一个Map ID
            String token = UUID.randomUUID().toString();

//            登录进来的user存入redis中
            RedisUtils.INSTANCE.set(token,JSON.toJSONString(user),60*30);

            Map<String,Object> map = new HashMap<>();
            map.put("uToken",token);
            map.put("User",user);
//            System.out.println(RedisUtils.INSTANCE.get(token));

            System.out.println(new AjaxResult(true,"登录成功",map));
            return new AjaxResult(true,"登录成功",map);
        }
    }


    @GetMapping("/search")
    public String search(@RequestParam String token){
        return RedisUtils.INSTANCE.get(token);
    }

    @GetMapping("/logout")
    private String logout(@RequestParam String token){
        RedisUtils.INSTANCE.del(token);
        return "成功注销";
    }

}
